from bs4 import BeautifulSoup
from utils.logger import setup_logger
from config.settings import BASE_URL

logger = setup_logger(__name__)

class HTMLParser:
    @staticmethod
    def parse_lpr_list(html_content):
        """解析LPR列表页面"""
        if not html_content:
            logger.error("HTML内容为空")
            return []
        
        try:
            soup = BeautifulSoup(html_content, 'html.parser')
            lpr_items = []
            
            tables = soup.find_all('table', {'width': '100%'})
            for table in tables:
                links = table.find_all('a', href=lambda x: x and '3876551' in x)
                for link in links:
                    title = link.get('title', '').strip()
                    href = link.get('href', '').strip()
                    date_span = link.find_next('span', class_='hui12')
                    date = date_span.text.strip() if date_span else ''
                    
                    if title and href and 'LPR' in title:
                        full_url = f"{BASE_URL}{href}"
                        lpr_items.append({
                            'title': title,
                            'url': full_url,
                            'date': date
                        })
                        logger.info(f"找到LPR信息: {title} ({date})")
            
            return lpr_items
        except Exception as e:
            logger.error(f"解析LPR列表时发生错误: {str(e)}")
            return []

    @staticmethod
    def parse_lpr_detail(html_content):
        """解析LPR详情页面"""
        if not html_content:
            logger.error("详情页HTML内容为空")
            return None
        
        try:
            soup = BeautifulSoup(html_content, 'html.parser')
            content_area = soup.find('div', attrs={'aria-label': '内容文本区'})
            
            if not content_area:
                logger.error("未找到内容区域")
                return None
                
            title = content_area.find('h2')
            title_text = title.text.strip() if title else ""
            
            zoom_div = content_area.find('div', id='zoom')
            if zoom_div:
                paragraphs = zoom_div.find_all('p')
                content_text = '\n'.join([p.text.strip() for p in paragraphs if p.text.strip()])
            
            if not (title_text and content_text):
                logger.error("未找到标题或内容")
                return None
                
            return {
                'title': title_text,
                'content': content_text
            }
            
        except Exception as e:
            logger.error(f"解析详情页时发生错误: {str(e)}")
            return None 